package com.project.utils;

import com.project.model.DeviceInfo;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author Sweey Zhang
 * @description
 * @date 2021/8/9 14:52
 */
public class Dom4jUtil {
    public static ArrayList parseDeviceInfo(String xml) {
        ArrayList<DeviceInfo> list = new ArrayList<DeviceInfo>();
        try {
            SAXReader reader = new SAXReader();//创建一个读取XML文件的对象
            Document document = reader.read(new File(xml));
            Element root = document.getRootElement();//获取根节点
            for (Iterator<Element> reRoot = root.elementIterator(); reRoot.hasNext(); ) {
                Element childElement = reRoot.next();//获取子节点
               if(!"Devices".equals(childElement.getName())){
                   continue;
               }
                for (Iterator<Element> reChildElement = childElement.elementIterator(); reChildElement.hasNext(); ) {
                    DeviceInfo demoEntity = new DeviceInfo();
                    Element dom = reChildElement.next();//获取子节点的下一节点
                    demoEntity.setId(Integer.parseInt(dom.attribute("id").getValue()));
                    demoEntity.setDeviceIp(dom.attribute("deviceIp").getValue());
                    demoEntity.setDevicePort(dom.attribute("devicePort").getValue());
                    demoEntity.setIp(dom.attribute("ip").getValue());
                    demoEntity.setName(dom.attribute("name").getValue());
                    demoEntity.setPassword(dom.attribute("password").getValue());
                    demoEntity.setPort(dom.attribute("port").getValue());
                    demoEntity.setType(dom.attribute("type").getValue());
                    demoEntity.setUser(dom.attribute("user").getValue());
                    list.add(demoEntity);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
